﻿<?php

$db=New tt();
//set_time_limit(0);
$sleep_time=20;

while(true){

        try
        {
            
            // 如果抛出异常，以下文本不会输出
           
            var_dump(date('Y-m-d h:i:s'));
           //$db->getWhereDate(); //运行获取转单
           // $db->zhiXing();  //运行提交抖音客资到呼叫系统 591和智迪
           // $db->getGuanDianTong(); //广点通数据提交 优居 和 广点通
           $db->getWxGongZhongHao(); //微信公众号提交
           $db->youJu();  //提交优居线索
           sleep($sleep_time);
        }
        catch(Exception $e)
        {
            echo 'Message: ' .$e->getMessage();
        }


       
}



    
// 在 try 块 触发异常

// 捕获异常


class tt{

    // 创建一个有异常处理的函数
    public function checkNum($number)
    {
        if($number>1)
        {
            throw new Exception("变量值必须小于等于 1");
        }
            return true;
    }

    public function zhiXing(){


        $arr=self::selectDouYindata();
        var_dump('tiJiao:'.count($arr));

        if(count($arr)>0)
        {

            for($i=0;$i<count($arr);$i++){

                $CusName=$arr[$i]['NAME'];
                $CusPhone=$arr[$i]['telphone'];
                $ChannelID=$arr[$i]['qudao'];
                $CusAddress=$arr[$i]['location'];
                $Remark='';
                $clue_id=$arr[$i]['clue_id'];

                $result=self::api($CusName,$CusPhone,$ChannelID,$CusAddress,$Remark);

                var_dump('jinDu:'.$i);

                if($result==1){

                    self::updateDouYindata($clue_id);

                }

            }

        }


    }


    public function api($CusName,$CusPhone,$ChannelID,$CusAddress,$Remark)
    {


        $data["CusName"]= $CusName;
        $data["CusPhone"]=$CusPhone;
        $data["ChannelID"]= $ChannelID;
        $data["CusAddress"]= $CusAddress;
        $data["Remark"]=$Remark;
        $data = json_encode($data);
        $pp["Service"] = "com.QM.CallCenter.CommonChannelAPI";
        $pp["Param"] = addslashes($data);

        $pp = json_encode($pp);
        $pp = str_replace('\\\\\\',"\\",$pp);

        $out = self::do_curl("https://capi.qumei.com/api/home/call",$pp,false,"POST");
        $out = json_decode($out,true);

        if ($out['StatusCode']==200){

            return 1;

        }else{

            return 2;

        }


    }


    public function do_curl($url, $params = array(), $upload = false, $type = 'POST')
    {

        $method = strtoupper($type);
        if ($method == 'GET') {
            $url = "{$url}?" . http_build_query($params);
        }
        $ch = curl_init();
        //curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        //输出主机头
        if ($url=="https://capi.qumei.com/api/home/call"){
            //定义请求类型
            $username="webuser";
            $password="Qumei1993";
            $timestamp=time();

            $sign = md5($username.",".$password.",".$timestamp);

            $token = file_get_contents("token.txt");

            $headers = array(
                "Content-Type: application/json",
                "Authorization: Bearer $token",
                "username: $username",
                "password: $password",
                "timestamp: $timestamp",
                "sign: $sign"
            );

            // var_dump($headers);

            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        // 是否检测服务器的证书是否由正规浏览器认证过的授权CA颁发的
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // 是否检测服务器的域名与证书上的是否一致
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

        if ($method == 'POST') {
            if ($upload) {        //设置上传文件
                $file = new \CURLFile($upload['tmp_name'], $upload['type'], $upload['name']);
                $params[$upload['get_name']] = $file;
            }
            //$params = '{"Service":"com.QM.CallCenter.CommonChannelAPI","Param":{\"CusName\":\"test591\u5ba2\u8d44\uff08\u8bf7\u5ffd\u7565\uff09\",\"CusPhone\":\"15107984564\",\"ChannelID\":\"1262592253055078400\",\"CusAddress\":\"\u5317\u4eac\",\"Remark\":\"\"}}';
            // var_dump($params);
            @curl_setopt($ch, CURLOPT_POST, 1);
            @curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        }

        $result = curl_exec($ch);
        //$request_header = curl_getinfo( $ch, CURLINFO_HEADER_OUT);
        //print_r($request_header);
        //打印发送头信息

        curl_close($ch);
        if ($result === null || $result === false) {

            $this->error('操作出错！');

        } else {

            return $result;

        }

    }



     //获取token
    public function gettoken()
    {
        $data = array();
        $data['grant_type']="password";
        $data['username']="webuser";
        $data['password']="Qumei1993";
        $out = do_curl("https://capi.qumei.com/token",$data,"","POST");
        $out = json_decode($out,true);
        file_put_contents("token.txt",$out["access_token"]);
        //var_dump($out["access_token"]);
    }



    public function selectDouYindata()
    {

        $qure="SELECT clue_id,NAME,city_name,telphone,qudao,location FROM douYinDbPhone WHERE isSub IS NULL;";

       
        $host='localhost';
        $user='root';
        $password='root';
        $database='weizandata';
        $link=mysqli_connect($host, $user, $password, $database);
        $link->query("set names utf8");
        $result=mysqli_query($link, $qure);
        $arr=mysqli_fetch_all($result, 1);
        // $json = json_encode(array(
        //         "code"=>0,
        //         "msg"=>'提交成功',
        //         "data"=>$result ),
        //         JSON_UNESCAPED_UNICODE);
        
        
        mysqli_close($link);


        return $arr;

    }
    public function updateDouYindata($clue_id)
    {

        $qure="UPDATE douYinDbPhone SET isSub=1 WHERE clue_id='{$clue_id}';";

       
        $host='localhost';
        $user='root';
        $password='root';
        $database='weizandata';
        $link=mysqli_connect($host, $user, $password, $database);
        $link->query("set names utf8");
        $result=mysqli_query($link, $qure);
        // $arr=mysqli_fetch_all($result, 1);
        // $json = json_encode(array(
        //         "code"=>0,
        //         "msg"=>'提交成功',
        //         "data"=>$result ),
        //         JSON_UNESCAPED_UNICODE);
        
        
        // mysqli_close($link);


        // return $arr;

    }


    private function selectCity($phone){


        $phoneD=substr($phone,0,7);
        $qure="SELECT CONCAT(province,city) AS city FROM phone WHERE phone='{$phoneD}';";
        $host='localhost';
        $user='root';
        $password='root';
        $database='phone';
        $link=mysqli_connect($host, $user, $password, $database);
        $link->query("set names utf8");
        $result=mysqli_query($link, $qure);
        $arr=mysqli_fetch_all($result, 1);
        mysqli_close($link);
        return $arr[0]['city'];
    }

    public function posturl($url,$data){

        $data  = json_encode($data);
        $headerArray = array("Content-Type: application/json");
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $put = curl_exec($curl);

       // echo $put;
        curl_close($curl);

        return $put;
    }

    public function getFiled($variable){

        $vali='';

        foreach ($variable as $key => $value) {
        
            $filed='';

            $val='';

            foreach ($variable[$key] as $key1 => $value1) {

                if(is_array($value1)){

                    $value1=json_encode($value1,JSON_UNESCAPED_UNICODE);

                    $value1=addslashes($value1);

                }



                $filed.=$key1.",";

                $val.="'".$value1."',";



            }

            $filed="(".substr($filed, 0,strlen($filed)-1).")";

            $vali.="(".substr($val, 0,strlen($val)-1)."),"; 

    

        }


        return ['file'=>$filed,'val'=>substr($vali,0,strlen($vali)-1)];
    }

    public function insertDb($qure){


        //$qure="UPDATE by_data SET isRead=1 WHERE callInstanceId in {$id};";

        //echo $qure;

        $host='localhost';
        $user='root';
        $password='root';
        $database='weizandata';
        $link=mysqli_connect($host, $user, $password, $database);
        $link->query("set names utf8");
        $result=mysqli_query($link, $qure);
        //$arr=mysqli_fetch_all($result, 1);

        //echo mysqli_error($link);

        return ["result"=>$result,"row"=>mysqli_affected_rows($link)];

    }

    public function getWhereDate(){

        $date=date('Y-m-d');

        $wher=['FromDate'=>$date,'ToDate'=>$date,'KeyWord'=>'','ChannelID'=>'','ConsultantName'=>''];

        $data=['SqlWhere'=>json_encode($wher,JSON_UNESCAPED_UNICODE),'PageNum'=>'0',"PageSize"=>'20'];

        $a=self::posturl('http://go.qumei.com/api/CRM/CustomerDataDetail',$data);

        $count=json_decode($a,true)['Data']['TotalCount'];

        $pageNum=ceil($count/20);

        $row=0;

        for($i=0;$i<=$pageNum;$i++){

            $data=['SqlWhere'=>json_encode($wher,JSON_UNESCAPED_UNICODE),'PageNum'=>$i,"PageSize"=>'20'];
            $a=self::posturl('http://go.qumei.com/api/CRM/CustomerDataDetail',$data);

            $variable=json_decode($a,true)['Data']['Data'];

            $sqlstr=self::getFiled($variable);

            $qure="INSERT IGNORE INTO zhuanDanPhone ".$sqlstr['file']." values ".$sqlstr['val'];

            $result=self::insertDb($qure);

            if($result["result"]){

                $row+=$result["row"];
            }


        }

        var_dump('update:'.$row) ;


        return $row ;


    }

    function getGuanDianTong(){

        $qure="SELECT * FROM gdtphone WHERE isSub IS NULL;";

        $host='localhost';
        $user='root';
        $password='root';
        $database='weizandata';
        $link=mysqli_connect($host, $user, $password, $database);
        $link->query("set names utf8");
        $result=mysqli_query($link, $qure);
        $arr=mysqli_fetch_all($result, 1);
        var_dump('GDTtiJiao:'.count($arr));
        if(count($arr)>0)
        {

            for($i=0;$i<count($arr);$i++){

                $CusName=$arr[$i]['leads_name'];
                $CusPhone=$arr[$i]['leads_tel'];
                $ChannelID=$arr[$i]['qudao'];
                $CusAddress=$arr[$i]['tel_location'];
                $Remark='';

                //$clue_id=$arr[$i]['clue_id'];

                $result=self::api($CusName,$CusPhone,$ChannelID,$CusAddress,$Remark);

                var_dump('GDTjinDu:'.$i);

                if($result==1){

                   self::updateGuanDianTong($CusPhone);

                }

            }

        }

    }


    function youJu(){

        $qure="SELECT * FROM youjuTell WHERE isSub IS NULL;";
        

        $host='localhost';
        $user='root';
        $password='root';
        $database='weizandata';
        $link=mysqli_connect($host, $user, $password, $database);
        $link->query("set names utf8");
        $result=mysqli_query($link, $qure);
        $arr=mysqli_fetch_all($result, 1);
        var_dump('YJtiJiao:'.count($arr));
        if(count($arr)>0)
        {

            for($i=0;$i<count($arr);$i++){

                $CusName=$arr[$i]['title'];
                $CusPhone=$arr[$i]['link_url'];
                // $ChannelID='1122785705056145408';优居渠道
                $ChannelID='1295239520261902336'; //改标签
                $CusAddress= self::selectCity($arr[$i]['link_url']);
                $Remark='';
                //$clue_id=$arr[$i]['clue_id'];
                $result=self::api($CusName,$CusPhone,$ChannelID,$CusAddress,$Remark);

                var_dump('YJjinDu:'.$i);

                if($result==1){

                   self::updateYoujuTell($CusPhone);

                }

            }

        }

    }

    function updateYoujuTell($phone){

        $qure="UPDATE youjuTell SET date_submit='".date('Y-m-d H:i:s')."',isSub=1 WHERE link_url='".$phone."';";

        $host='localhost';
        $user='root';
        $password='root';
        $database='weizandata';
        $link=mysqli_connect($host, $user, $password, $database);
        $link->query("set names utf8");
        $result=mysqli_query($link, $qure);

        return $result;


    }

    function updateGuanDianTong($phone){

        $qure="UPDATE gdtphone SET submit_date='".date('Y-m-d H:i:s')."',isSub=1 WHERE leads_tel='".$phone."';";

        $host='localhost';
        $user='root';
        $password='root';
        $database='weizandata';
        $link=mysqli_connect($host, $user, $password, $database);
        $link->query("set names utf8");
        $result=mysqli_query($link, $qure);

        return $result;


    }
    function getWxGongZhongHao(){

        $qure="SELECT showname,mobile FROM wxgongzhonghaophone WHERE isSub IS NULL;";

        $host='localhost';
        $user='root';
        $password='root';
        $database='weizandata';
        $link=mysqli_connect($host, $user, $password, $database);
        $link->query("set names utf8");
        $result=mysqli_query($link, $qure);
        $arr=mysqli_fetch_all($result, 1);
        var_dump('WXtiJiao:'.count($arr));
        if(count($arr)>0)
        {

            for($i=0;$i<count($arr);$i++){

                $CusName=$arr[$i]['showname'];
                $CusPhone=$arr[$i]['mobile'];
                $ChannelID='1122784557712674816';
                $CusAddress=self::selectCity($arr[$i]['mobile']);
                $Remark='';

                //$clue_id=$arr[$i]['clue_id'];

                $result=self::api($CusName,$CusPhone,$ChannelID,$CusAddress,$Remark);

                var_dump('GDTjinDu:'.$i);

                if($result==1){

                   self::updateWxGongZhongHao($CusPhone);

                }

            }

        }

    }


    function updateWxGongZhongHao($phone){

        $qure="UPDATE wxgongzhonghaophone SET submit_date='".date('Y-m-d H:i:s')."',isSub=1 WHERE mobile='".$phone."';";

        $host='localhost';
        $user='root';
        $password='root';
        $database='weizandata';
        $link=mysqli_connect($host, $user, $password, $database);
        $link->query("set names utf8");
        $result=mysqli_query($link, $qure);

        return $result;


    }



}